import { useMemo } from 'react'
import { useSearchParams, URLSearchParamsInit } from 'react-router-dom'
import { clearEmptyKey } from 'utils'

/**
 * 返回页面url中,指定键的参数值
 */

export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams()

  return [
    useMemo(
      // 返回一个对象
      () =>
        keys.reduce((prev, key) => {
          return { ...prev, [key]: searchParams.get(key) || '' }
        }, {} as { [key in K]: string }),
      [searchParams]
    ),
    // 设置searchParam的方法
    (params: Partial<{ [key in K]: unknown }>) => {
      const o = clearEmptyKey({ ...Object.fromEntries(searchParams), ...params }) as URLSearchParamsInit
      setSearchParams(o)
    }
  ] as const
}
